<!doctype HTML>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<style>
#textarea, #plaintext, #richedit {
  font-family: 'Courier', monospace;
  width: 10ch;
}
#plaintext, #richedit {
  border: 1px solid black;
  white-space: pre-wrap;
}
</style>
<textarea id="textarea"></textarea>
<div id="plaintext" contenteditable="plaintext-only"></div>
<div id="richedit" contenteditable></div>
<script>
function runInElement(element, before, after, expected) {
  test(() => {
    let offset = before.length;
    let acutal;
    if (element.tagName === 'TEXTAREA') {
      element.value = before + after;
      element.focus();
      element.setSelectionRange(offset, offset);
      eventSender.keyDown(' ');
      actual = element.value;
    } else {
      element.textContent = before + after;
      let textNode = element.firstChild;
      window.getSelection().setBaseAndExtent(textNode, offset, textNode, offset);
      eventSender.keyDown(' ');
      actual = element.textContent;
    }
    assert_equals(actual, before + (expected ? '\n ' : ' ') + after);
  }, `Typing space at "${before}|${after}" ${expected ? 'should' : 'should not'} insert a line break in ${element.id}`);
}

function run(before, after, expected) {
  runInElement(textarea, before, after, expected);
  runInElement(plaintext, before, after, expected);
  runInElement(richedit, before, after, false);
}

(function () {
  if (!window.eventSender) {
    test(function () {
      assert_unreached();
    }, 'This test requires eventSender');
    return;
  }

  run('123456789 ', 'XY', true);
  run('12345     ', 'XY', true);
  run('12345        ', 'XY', true);
  run('123456789-', 'XY', false);
})();
</script>
